import telnetlib

HOST = "192.168.1.199"
USER = b"admin"
PASS = b"admins"
ENABLE = b"enable"
COMMAND = b"show version"

#将字符串中的“\r\r”替换为“\r”
def change(b):
    a = b.decode()
    return a.replace('\r\r', '\r')


try:
    # 使用telnet连接远程IP
    tn = telnetlib.Telnet(HOST)
except TimeoutError:
    # 获取超时异常
    print("发生连接超时异常")
else:
    # 设置打印等级
    tn.set_debuglevel(0)
    # 输入命令
    tn.read_until(b"User:")
    tn.write(USER + b'\n')
    tn.read_until(b"Password:")
    tn.write(PASS + b'\n')
    tn.read_until(b"(router) >")
    tn.write(ENABLE + b'\n')
    tn.read_until(b"Password:")
    tn.write(ENABLE + b'\n')
    tn.write(b'show run\n')
    tn.write(b'show version\n')
    tn.write(b'exit\n')
    # 打印返回值
    print(change(tn.read_all()))
    # 关闭telnet连接，节约资源
    tn.close()
